# -*- coding: utf8 -*-
from flask.blueprints import Blueprint
from flask.helpers import make_response
from flask.templating import render_template
from flask import request
import logging
import os

from ned_app.nmj_access import getNMJInterface


LOGGER=logging.getLogger(__name__)
main_blueprint = Blueprint('main', __name__,
					template_folder='main/templates', static_folder='main/static', url_prefix="/main")
main_blueprint._static_url_path = main_blueprint.static_url_path
@main_blueprint.route('/')
def home():
	nmj = getNMJInterface()
	libraries=[]
	for lib in nmj.get_libraries():
		to_show=lib
		LOGGER.info("lib = %s", lib)
		to_show.update({
			"image" : os.path.join("/main/libposter", lib["id"], os.path.basename(lib["image"])),
			"url" : "/library/%s" % lib["id"],
		})
		libraries.append(to_show)
	LOGGER.debug("libraries = %s", libraries)

	return render_template('pages/home.html', libraries=libraries)


@main_blueprint.route('/libposter/<lib_id>/<poster_filename>')
def get_poster(lib_id, poster_filename):
	LOGGER.info("retreive poster for lib %s", lib_id)
	nmj = getNMJInterface()
	lib = nmj.get_library(lib_id)
	resp = make_response(open(lib.export()["image"]).read())
	resp.content_type = "image/jpeg"
	return resp

def get_blueprint():
	return main_blueprint


def shutdown_server():
	func = request.environ.get('werkzeug.server.shutdown')
	if func is None:
		raise RuntimeError('Not running with the Werkzeug Server')
	func()
	
@main_blueprint.route('/shutdown') #, methods=['POST'])
def shutdown():
	getNMJInterface().stop()
	shutdown_server()
	return 'Server shutting down...'

